package ecustom.finance.actions;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import ecustom.clients.k3client.K3WebApiClient;
import ecustom.clients.k3client.entities.ERPPAYBILLReq;
import ecustom.clients.k3client.entities.ERPPAYBILLReq.FPAYBILLENTRY;
import ecustom.clients.util.JsonUtil;
import ecustom.common.AbstractAction;
import ecustom.common.CustomMap;
import ecustom.common.conn.DB;
import ecustom.common.servicelog.bean.ServiceLogBean;
import ecustom.common.util.CustomUtil;
import ecustom.finance.bean.FinanceBean;
import weaver.file.Prop;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.Row;

/**
* @author 作者:Gcc
* @createDate 创建时间：Aug 14, 2023 11:49:00 PM
*/
public class RCFYBXAction extends AbstractAction{
	
	private static final Logger log = Logger.getLogger(RCFYBXAction.class); 

	@Override
	public void process(RequestInfo requestInfo) throws Exception {
		Property[] mainFields = requestInfo.getMainTableInfo().getProperty();
		
		if(super.getMainInteger(mainFields, "sftserp") == 1) return;	// 是否推送ERP：0:是；否：1
		if(CustomUtil.isNotBlank(super.getMainString(mainFields, "erpNumber"))) return;	// ERP编码为空的情况，不重复推送给ERP
		
		handlERPData(requestInfo, mainFields);
	}
	
	public void handlERPData(RequestInfo requestInfo, Property[] mainFields) throws Exception {
		ServiceLogBean logBean = new ServiceLogBean("RCFYBXAction", "ecustom.finance.actions.RCFYBXAction-日常费用报销-推送ERP付款单",  "K3Cloud", "", System.currentTimeMillis());
		String formid = Prop.getPropValue("ecustom", "k3.fkd.formid");
		
		ERPPAYBILLReq req = setAYBILLReq(requestInfo, mainFields);
		log.info("outReq"+JsonUtil.toJson(req));
		Map<String, Object> erpResult = K3WebApiClient.saveData(logBean, req, formid);
		
		Integer requestId = requestInfo.getRequestManager().getRequestid();
		int formId = requestInfo.getRequestManager().getFormid();
		updateTable(formId, requestId, erpResult);
	}
	
	public ERPPAYBILLReq setAYBILLReq(RequestInfo requestInfo, Property[] mainFields) throws Exception, Exception {
		String fqzz = FinanceBean.getERPOrgNumber(super.getMainStringCK(mainFields, "fqzz", "发起组织不能为空！"));	// 所属公司
		String wldwlx = super.getMainStringCK(mainFields, "wldwlx", "往来单位类型不能为空！");	// 往来单位类型
		String wldw = FinanceBean.getERPWldw(super.getMainStringCK(mainFields, "wldw", "往来单位不能为空！"), wldwlx);	// 往来单位
		String skdwlx = super.getMainStringCK(mainFields, "skdwlx", "收款单位类型不能为空！");	// 收款单位类型
		String skdw = FinanceBean.getERPWldw(super.getMainStringCK(mainFields, "skdw", "收款单位不能为空！"), skdwlx);	// 往来单位
		String bb = super.getMainStringCK(mainFields, "jsbb", "报销币别不能为空！");	// 币别
		String sfwlfy = super.getMainStringCK(mainFields, "sfwlfy", "是否往来费用不能为空！");	// 是否往来费用
		if("0".equals(sfwlfy)) {
			sfwlfy = "1";
		}else if("1".equals(sfwlfy)){
			sfwlfy = "2";
		}
		String bz = super.getMainString(mainFields, "bz");	// 备注
		
		ERPPAYBILLReq repPUR = new ERPPAYBILLReq();   
		repPUR.setIsAutoSubmitAndAudit("true");	// 审核
		repPUR.getModel().setFID(0);	// 实体主键，有实体主键为修改操作，没有则新建
		repPUR.getModel().getFBillTypeID().put("FNUMBER", "FKDLX04_SYS");
		repPUR.getModel().setFDATE(CustomUtil.getStringDate());	// 单据时间
		repPUR.getModel().setFCONTACTUNITTYPE(wldwlx);	// 往来单位类型
		repPUR.getModel().getFCONTACTUNIT().put("FNumber", wldw);	// 往来单位
		repPUR.getModel().setFRECTUNITTYPE(skdwlx);	// 收款单位类型
		repPUR.getModel().getFRECTUNIT().put("FNumber", skdw);	// 收款单位
		repPUR.getModel().getFSETTLEORGID().put("FNumber", fqzz);	// 结算组织
		repPUR.getModel().getFPAYORGID().put("FNumber", fqzz);	// 付款组织
		repPUR.getModel().getFCURRENCYID().put("FNumber", bb);	// 币别
		repPUR.getModel().getFSETTLECUR().put("FNUMBER", bb);	// 结算币别
		repPUR.getModel().getFSETTLEMAINBOOKID().put("FNUMBER", "PRE001");	// 结算本位币，固定人民币：币别
		
		repPUR.getModel().setF_SZXY_OARequestID(requestInfo.getRequestManager().getRequestid()+"");	// OAID
		repPUR.getModel().setF_SZXY_Combo(sfwlfy);	// 是否往来费用
		// 2023-11-30 新增去除特殊符号
		repPUR.getModel().setFREMARK(FinanceBean.delHTMLTag(FinanceBean.subRemark(bz)));		// 备注
		
		repPUR.getModel().setFDOCUMENTSTATUS("Z");	// 单据状态：固定-Z
		repPUR.getModel().setFBUSINESSTYPE("3");	// 业务类型：固定-3
		repPUR.getModel().setFCancelStatus("A");	// 作废状态，默认：A
		// 
		repPUR.getModel().setFPAYBILLENTRY(getFPAYBILLENTRY(requestInfo, mainFields, repPUR));
		return repPUR;
	}
	
	/**
	 * TODO 
	 * 赋值明细表
	 * @param requestInfo
	 * @param mainFields
	 * @param jsfs	结算方式
	 * @param fkyt	付款用途
	 * @return
	 * @throws Exception
	 * @throws Exception
	 */
	public List<FPAYBILLENTRY> getFPAYBILLENTRY(RequestInfo requestInfo, Property[] mainFields, ERPPAYBILLReq repPUR) throws Exception, Exception {
		Integer requestid = requestInfo.getRequestManager().getRequestid();
		int formid = requestInfo.getRequestManager().getFormid();
		Map<String, Object> maxAmountMap = FinanceBean.getRCFYMaxAmount(formid, "DT1", requestid);
		String rowId = CustomUtil.getString(maxAmountMap.get("ID"));
		
		String jsfs = FinanceBean.getERPJsfs(super.getMainStringCK(mainFields, "jsfs", "结算方式不能为空！"));	// 结算方式
		String dfyhzh = super.getMainString(mainFields, "dfyhzh");	// 对方银行账号
		String dfyhmc = super.getMainString(mainFields, "dfyhmc");	// 对方账户名称
		String wfyxzh = FinanceBean.getERPYhzh(super.getMainString(mainFields, "wfyxzh"));	// 我方银行账号
		String yxwd = super.getMainString(mainFields, "yxwd");	// 对方银行网点
		
		DetailTable  detailTable = requestInfo.getDetailTableInfo().getDetailTable(0);
		List<FPAYBILLENTRY> listFEntity = new ArrayList<FPAYBILLENTRY>();
		for(Row row: detailTable.getRow()) {
			String fycdbm = FinanceBean.getERPDeptNumberV2(super.getCellString(row, "fycdbm"));	// 费用承担部门
			String fyxm = FinanceBean.getERPFyxm(super.getCellString(row, "fyxm"));	// 费用项目
			//Double sphl = super.getCellDoubleCK(row, "sphl", "审批汇率不能为空！");	// 汇率
			Double sphl = super.getCellDoubleCK(row, "sqhl", "申请汇率不能为空！");	// 申请汇率
			Double fyje = super.getCellDoubleCK(row, "fyje", "费用金额不能为空！") * sphl;	// 费用金额
			Double yfje = super.getCellDoubleCK(row, "yfje", "应付金额不能为空！") * sphl;	// 应付金额
			Double fkje = super.getCellDoubleCK(row, "fkje", "付款金额不能为空！") * sphl;	// 付款金额
			String invoiceNumbers = super.getCellString(row, "fph");	// 发票号
			String rkqj = super.getCellString(row, "rkqj");	// 报销内容
			
			FPAYBILLENTRY entry = new FPAYBILLENTRY();
			if(CustomUtil.isNotBlank(jsfs)) {
				entry.getFSETTLETYPEID().put("FNumber", jsfs);;	// 结算方式
			}
			entry.getFPURPOSEID().put("FNumber", "SFKYT10_SYS");;	// 付款用途：固定费用报销
			if(CustomUtil.isNotBlank(fyxm)) {
				entry.getFCOSTID().put("FNumber", fyxm);;	// 费用项目
			}
			if(CustomUtil.isNotBlank(fycdbm)) {
				entry.getFEXPENSEDEPTID_E().put("FNumber", fycdbm);;	// 费用承担部门
			}
			if(CustomUtil.isNotBlank(wfyxzh)) {
				entry.getFACCOUNTID().put("FNumber", wfyxzh);;	// 我方银行账号
			}
			entry.setFOPPOSITEBANKACCOUNT(dfyhzh);	// 对方银行账号
			entry.setFOPPOSITECCOUNTNAME(dfyhmc);	// 对方账户名称
			if(CustomUtil.isNotBlank(yxwd)) {
				entry.getFBankDetail().put("FNUMBER", yxwd);	// 银行网点
			}
			
			entry.setFCOMMENT(FinanceBean.delHTMLTag(FinanceBean.subRemark(rkqj)));	// 备注
			entry.setFRecType("1");	// 收款类型：固定个人
			entry.setFRuZhangType("1");	// 入账类型：固定并笔入账
			entry.setFPOSTDATE(CustomUtil.getStringDate());	// 登账日期
			
			// 发票费用明细
			Map<String, Object> invoiceMap = handlInvoiceDetail(invoiceNumbers, entry, rkqj, sphl);
			List<FPAYBILLENTRY> invoiceDetail = (List<FPAYBILLENTRY>)invoiceMap.get("invoiceDetail");
			Double taxsum = CustomUtil.getDouble(invoiceMap.get("taxsum"));	// 发票汇总进项税
			
			entry.setF_SZXY_Amount(fyje-taxsum);	// 费用金额
			entry.setFPAYAMOUNTFOR_E(fkje-taxsum);	// 付款金额
			entry.setFPAYTOTALAMOUNTFOR(yfje-taxsum);	// 应付金额
			entry.setF_SZXY_Amount1(0.0);	// 进项税
			
			listFEntity.add(entry);	// 添加费用金额明细
			if(CustomUtil.isNotBlank(invoiceDetail)) {
				listFEntity.addAll(invoiceDetail);	// 将发票费用明细写入到ERP里面
			}
		}
		
		return listFEntity;
	}
	
	/**
	 * 处理发票费用明细
	 * @param invoiceNumbers
	 * @param entry
	 * @param taxSum
	 * @return
	 * @throws Exception
	 */
	private Map<String, Object> handlInvoiceDetail(String invoiceNumbers, FPAYBILLENTRY entry, String rkqj, Double sphl) throws Exception {
		Map<String, Object> objMap = new HashMap<String, Object>();
		Double taxSum = 0.0;
		List<FPAYBILLENTRY> invoiceDetail = new ArrayList<FPAYBILLENTRY>();
		List<CustomMap> invoiceMap = FinanceBean.getInvoiceData(invoiceNumbers);	// 发票号码
		if(CustomUtil.isNotBlank(invoiceMap)) {
			for(CustomMap map : invoiceMap) {
				Double tax = map.getDouble("DTAX") * sphl;
				if(CustomUtil.isNotBlank(tax) && tax > 0) {
					FPAYBILLENTRY newEntry = new FPAYBILLENTRY();
					if(CustomUtil.isNotBlank(entry.getFSETTLETYPEID().get("FNumber"))) {
						newEntry.getFSETTLETYPEID().put("FNumber", entry.getFSETTLETYPEID().get("FNumber"));;	// 结算方式
					}
					if(CustomUtil.isNotBlank(entry.getFPURPOSEID().get("FNumber"))) {
						newEntry.getFPURPOSEID().put("FNumber", entry.getFPURPOSEID().get("FNumber"));;	// 付款用途
					}
					if(CustomUtil.isNotBlank(entry.getFCOSTID().get("FNumber"))) {
						newEntry.getFCOSTID().put("FNumber", entry.getFCOSTID().get("FNumber"));;	// 费用项目
					}
					if(CustomUtil.isNotBlank(entry.getFEXPENSEDEPTID_E().get("FNumber"))) {
						newEntry.getFEXPENSEDEPTID_E().put("FNumber", entry.getFEXPENSEDEPTID_E().get("FNumber"));;	// 费用承担部门
					}
					if(CustomUtil.isNotBlank(entry.getFACCOUNTID().get("FNumber"))) {
						newEntry.getFACCOUNTID().put("FNumber", entry.getFACCOUNTID().get("FNumber"));;	// 我方银行账号
					}
					newEntry.setFOPPOSITEBANKACCOUNT(entry.getFOPPOSITEBANKACCOUNT());	// 对方银行账号
					newEntry.setFOPPOSITECCOUNTNAME(entry.getFOPPOSITECCOUNTNAME());	// 对方账户名称
					
					newEntry.setFCOMMENT(FinanceBean.subRemark(rkqj));	// 备注
					newEntry.setFRecType("1");	// 收款类型：固定个人
					newEntry.setFRuZhangType("1");	// 入账类型：固定并笔入账
					newEntry.setFPOSTDATE(CustomUtil.getStringDate());	// 登账日期
					FinanceBean.setInputTax(newEntry, map.getString("INVOICETYPE"));	// 进项税类型：0：税一；1：税二
					newEntry.setF_SZXY_NoteInvNO(map.getString("INVOICENUMBER"));	// 备注发票号
					
					newEntry.setF_SZXY_Amount(null);	// 费用金额
					newEntry.setF_SZXY_Amount1(tax);	// 进项税，传发票的增值税
					newEntry.setFPAYTOTALAMOUNTFOR(null);	// 应付金额
					invoiceDetail.add(newEntry);
					log.info("invoiceDetail-newEntry:"+JsonUtil.toJson(newEntry));
					taxSum = CustomUtil.add(taxSum, tax);	// 进项税累加
				}
				
			}
		}
		
		// entry.setF_SZXY_Amount1(taxSum);	// 合计进项税，传发票的增值税
		objMap.put("taxsum", taxSum);
		objMap.put("invoiceDetail", invoiceDetail);
		return objMap;
	}
	
	private int updateTable(Integer formId, Integer requestId, Map<String, Object> erpResult) throws SQLException {
		Integer erpFID = CustomUtil.getInteger(erpResult.get("FID"));
		String erpNumber = CustomUtil.getString(erpResult.get("Number"));
		String tableName = "FORMTABLE_MAIN_" + Math.abs(formId);
		String updateSql = "UPDATE "+tableName+" SET ERPFID=?, ERPNUMBER=? WHERE REQUESTID=?";
		int i = DB.conn().executeUpdate(updateSql, erpFID, erpNumber, requestId);
		return i;
	}

}
